﻿using System;
using System.Collections.Generic;
using RpcClient.Interface;
using RpcClient.Model;
using RpcModel;

namespace RpcModular.Accredit
{
    internal class AccreditExtendService : IExtendService
    {
        private readonly IAccreditController _Service;

        public AccreditExtendService(IAccreditController service)
        {
            this._Service = service;
        }

        public string Name => "AccreditService";

        public void Load(IRpcService service)
        {
            service.LoadExtend += this._Service_LoadExtend;
            service.ReceiveEnd += this._Service_ReceiveEnd;
            service.ReceiveMsg += this._Service_ReceiveMsg;
        }
        private void _Service_ReceiveMsg(IMsg msg)
        {
            if (msg.Extend != null && msg.Extend.TryGetValue("AccreditId", out string val))
            {
                _Service.SetAccredit(new Guid(val));
            }
            else
            {
                _Service.SetAccredit(null);
            }
        }

        private void _Service_LoadExtend(string dictate, ref Dictionary<string, string> extend)
        {
            if (_Service.AccreditId.HasValue)
            {
                extend.Add("AccreditId", _Service.AccreditId.Value.ToString());
            }
        }
        private void _Service_ReceiveEnd(IMsg msg, TcpRemoteReply reply)
        {
            this._Service.ClearAccredit();
        }
    }
}
